﻿#include "purchasewidget.h"
#include "ui_purchasewidget.h"
#include "sqlhelp.h"
#include "goodsqlhelp.h"
#include "myhelper.h"
#include "basicdatawidget.h"
#include "commonhelper.h"
#include "recvtablemodel.h"
#include "tableInfo.h"
#include "modifydialog.h"
#include "excel.h"
#include <QDebug>
#include <QStandardItemModel>
#include <QCompleter>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QKeyEvent>
#include <QProgressBar>
#include <QPropertyAnimation>

PurchaseWidget::PurchaseWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PurchaseWidget)
{
    ui->setupUi(this);
    this->InitForm();
    this->InitParamete();
    this->CreateConnect();
}

PurchaseWidget::~PurchaseWidget()
{
    delete ui;
}

void PurchaseWidget::InitForm()
{
    m_pGoodsSqlhelp = new GoodSqlHelp();
    m_pBascWidget = new BasicDataWidget();
    m_pStandModel = new RecvTableModel();
    ui->tableView->setModel(m_pStandModel);
    initTableView(ui->tableView);
    m_popMenu = new QMenu(this);
    m_actionCode = new QAction("为此商品添加新条码",this);
    m_popMenu->addAction(m_actionCode);
}

void PurchaseWidget::InitParamete()
{
    ui->Goods_Id_lineEdit->setValidator(new QRegularExpressionValidator(
                                            QRegularExpression("[A-Z0-9]{10,10}"), this));  //限制商品Id输入
    ui->Goods_BarCode_lineEdit->setValidator(new QRegularExpressionValidator(
                                                 QRegularExpression("[0-9]{8,20}"), this));  //限制条形码输入
    ui->Goods_FullName_lineEdit->setValidator(new QRegularExpressionValidator(
                                                  QRegularExpression("^[\u4E00-\u9FA5]{1,20}$"), this));  //限制全称输入
    ui->Goods_SimpleName_lineEdit->setValidator(new QRegularExpressionValidator(
                                                  QRegularExpression("^[\u4E00-\u9FA5]{1,10}$"), this));  //限制简称输入
    ui->Goods_SellPrice_lineEdit->setValidator(new QDoubleValidator(0,1000000,2,this));   //限制售价输入
    ui->Goods_EnterPrice_lineEdit->setValidator(new QDoubleValidator(0,1000000,2,this));   //限制进价输入
    m_pGoodsSqlhelp->BindDataToCombox(g_unitTableName, g_unitColumn[Unit_Name],
                                      g_unitColumn[Unit_Id], ui->Goods_Units_comboBox); //绑定单位
    m_pGoodsSqlhelp->BindDataToCombox(g_categorieTableName, g_CategorieColumn[Categorie_Name],
                                      g_CategorieColumn[Categorie_Id], ui->Goods_Categories_comboBox); //绑定种类

    ui->multBarCode_toolButton->setIcon(QIcon(":/image/sysButtom/add.png"));
    ui->multBarCode_toolButton->setIconSize(QSize(20,20));
    ui->multBarCode_toolButton->setToolTip("添加多个");

    ui->lineEdit->installEventFilter(this);
    ui->tableView->installEventFilter(this);

    this->setProgressBarQss(ui->progressBar);
    ui->progressBar->setVisible(false);

}

void PurchaseWidget::CreateConnect()
{
    connect(m_actionCode, SIGNAL(triggered(bool)), this, SLOT(addBarCode(bool)));
}

void PurchaseWidget::initTableView(QTableView *tableView, int rowHeight, bool headVisible, bool edit)
{
   //奇数偶数行颜色交替
   tableView->setAlternatingRowColors(true);
   //垂直表头是否可见
   tableView->verticalHeader()->setVisible(headVisible);
   //选中一行表头是否加粗
   tableView->horizontalHeader()->setHighlightSections(false);
   //最后一行拉伸填充
   tableView->horizontalHeader()->setStretchLastSection(true);
   //行标题最小宽度尺寸
   tableView->horizontalHeader()->setMinimumSectionSize(0);
   //行标题最大高度
   tableView->horizontalHeader()->setMaximumHeight(rowHeight);
   //默认行高
   tableView->verticalHeader()->setDefaultSectionSize(rowHeight);
   //选中时一行整体选中
   tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
   //只允许选择单个
   tableView->setSelectionMode(QAbstractItemView::SingleSelection);

   //表头不可单击
#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
   tableView->horizontalHeader()->setSectionsClickable(false);
#else
   tableView->horizontalHeader()->setClickable(false);
#endif
   //鼠标按下即进入编辑模式
   if (edit) {
       tableView->setEditTriggers(QAbstractItemView::CurrentChanged | QAbstractItemView::DoubleClicked);
   } else {
       tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
   }
}

QString PurchaseWidget::setProgressBarQss(QProgressBar *bar, int barHeight, int barRadius, int fontSize,
                                          const QString &normalColor, const QString &chunkColor)
{
    QStringList list;
    list.append(QString("QProgressBar{font:%1pt;background:%2;max-height:%3px;border-radius:%4px;text-align:center;border:1px solid %2;}")
                .arg(fontSize).arg(normalColor).arg(barHeight).arg(barRadius));
    list.append(QString("QProgressBar:chunk{border-radius:%2px;background-color:%1;}")
                .arg(chunkColor).arg(barRadius));

    QString qss = list.join("");
    bar->setStyleSheet(qss);
    return qss;
}


//删除一行商品信息
void PurchaseWidget::on_Delete_pushButton_clicked()
{
    int row = ui->tableView->currentIndex().row();
    if( row < 0) {
        myHelper::ShowMessageBoxError("请先选择一行信息！");
        return;
    }
    int result = myHelper::ShowMessageBoxQuesion("确定删除此信息？");
    if(result == 0) //用户取消删除
        return;

    QString barCode = m_pStandModel->getBarCode(row);
    QString goodId = m_pStandModel->getGoodId(row);
    if(!m_pGoodsSqlhelp->removeGoodDate(goodId, barCode)) {
         myHelper::ShowMessageBoxError("删除失败!");
         return;
    }
    m_pStandModel->removeCurrentRowData(row);
}


//商品主档查询
void PurchaseWidget::on_Query_pushButton_clicked()
{
    QString filter = ui->lineEdit->text();
    QStringList headList;
    QList<QStringList> dataList;
    if(!m_pGoodsSqlhelp->queryGoods(filter,headList, dataList))
        myHelper::ShowMessageBoxError("查询失败!");
    //xdebug << dataList;
    m_pStandModel->clearData();
    m_pStandModel->setTableData(dataList);
}

//添加商品
void PurchaseWidget::on_pbnAddGoodsOk_clicked()
{
    //获取信息并判断
    QString goodBarCode = ui->Goods_BarCode_lineEdit->text().trimmed();
    QStringList infoList; //根据数据库有序添加数据
    infoList << ui->Goods_Id_lineEdit->text().trimmed()
             << ui->Goods_FullName_lineEdit->text().trimmed()
             << ui->Goods_SimpleName_lineEdit->text().trimmed()
             << ui->Goods_GoodCountspinBox->text().trimmed()
             << ui->Goods_Units_comboBox->currentData().toString().trimmed()
             << ui->Goods_Categories_comboBox->currentData().toString().trimmed()
             << ui->Goods_SellPrice_lineEdit->text().trimmed()
             << ui->Goods_EnterPrice_lineEdit->text().trimmed()
             << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    foreach (const QString &info, infoList) {
        if(info == "" || goodBarCode == "") {
            myHelper::ShowMessageBoxError("信息不完整");
            return;
        }
    }
    //查找此编号是否已存在
    QString info;
    if(m_pGoodsSqlhelp->istGoodIdExist(ui->Goods_Id_lineEdit->text().trimmed(), info)) {
        myHelper::ShowMessageBoxError(info);
        return;
    }
    //xdebug << InfoList;
    if(m_pGoodsSqlhelp->addGood(infoList, goodBarCode)) {   //添加数据库
        myHelper::ShowMessageBoxInfo("添加成功");
        infoList[Good_Units] = ui->Goods_Units_comboBox->currentText();
        infoList[Good_Categories] = ui->Goods_Categories_comboBox->currentText();
        m_pStandModel->insertOneRow(infoList, goodBarCode); //添加模型
        return;
    } else {
        myHelper::ShowMessageBoxError("添加失败");
        return;
    }
    myHelper::ShowMessageBoxError("未知错误-添加失败");
}


void PurchaseWidget::on_Modefy_pushButton_clicked()
{
    int row = ui->tableView->currentIndex().row();
    if( row < 0) {
        myHelper::ShowMessageBoxError("请先选择一行信息！");
        return;
    }
    QStringList  dataList = m_pStandModel->getData(row);
    ModifyDialog *modifyDialog = new ModifyDialog(dataList, m_pStandModel, row);
    modifyDialog->exec();
}

//增加单位
void PurchaseWidget::on_addUnit_pushButton_clicked()
{
    QString value = myHelper::showInputBox("添加单位","新单位名称:");
    if(value == "") {
        return;
    }
    //xdebug << value;
    if(!m_pGoodsSqlhelp->addUnit(value)) {
        myHelper::ShowMessageBoxError("添加失败");
        return;
    }
    //重新绑定单位
    ui->Goods_Units_comboBox->clear();
    m_pGoodsSqlhelp->BindDataToCombox(g_unitTableName, g_unitColumn[Unit_Name],
                                      g_unitColumn[Unit_Id], ui->Goods_Units_comboBox);
}

//增加种类
void PurchaseWidget::on_addCategorie_pushButton_clicked()
{
    QString value = myHelper::showInputBox("添加种类","新种类名称:");
    if(value == "")
        return;
    //xdebug << value;
    if(!m_pGoodsSqlhelp->addCategorie(value)) {
        myHelper::ShowMessageBoxError("添加失败");
        return;
    }
    //重新绑定种类
    ui->Goods_Categories_comboBox->clear();
    m_pGoodsSqlhelp->BindDataToCombox(g_categorieTableName, g_CategorieColumn[Categorie_Name],
                                      g_CategorieColumn[Categorie_Id], ui->Goods_Categories_comboBox);
}

//删除单位
void PurchaseWidget::on_deleteUnit_pushButton_clicked()
{
     QString text = ui->Goods_Units_comboBox->currentText();
    if(QDialog::Accepted != myHelper::ShowMessageBoxQuesion(QString("确定删除'%1'？").arg(text)))
        return;
    int unitId = ui->Goods_Units_comboBox->currentData().toInt();
    if(m_pGoodsSqlhelp->deleteUnit(unitId)) {
        myHelper::ShowMessageBoxInfo(QString("删除单位'%1'成功").arg(text));
        //重新绑定单位
        ui->Goods_Units_comboBox->clear();
        m_pGoodsSqlhelp->BindDataToCombox(g_unitTableName, g_unitColumn[Unit_Name],
                                          g_unitColumn[Unit_Id], ui->Goods_Units_comboBox);
    } else {
        myHelper::ShowMessageBoxError(QString("删除单位'%1'失败").arg(text));
    }
    return;
}

//删除种类
void PurchaseWidget::on_deleteCategorie_pushButton_clicked()
{
    QString text = ui->Goods_Categories_comboBox->currentText();
    if(QDialog::Accepted != myHelper::ShowMessageBoxQuesion(QString("确定删除'%1'？").arg(text)))
        return;
    int categorieId = ui->Goods_Categories_comboBox->currentData().toInt();
    if(m_pGoodsSqlhelp->deleteCategorie(categorieId)) {
        myHelper::ShowMessageBoxInfo(QString("删除种类'%1'成功").arg(text));
        //重新绑定种类
        ui->Goods_Categories_comboBox->clear();
        m_pGoodsSqlhelp->BindDataToCombox(g_categorieTableName, g_CategorieColumn[Categorie_Name],
                                          g_CategorieColumn[Categorie_Id], ui->Goods_Categories_comboBox);
    } else {
        myHelper::ShowMessageBoxError(QString("删除种类'%1'失败").arg(text));
    }
    return;
}


//添加多个条码
void PurchaseWidget::on_multBarCode_toolButton_clicked()
{
    QString newBarCode = myHelper::showInputBox("添加条码", "新条码");
    xdebug << newBarCode;
    if(newBarCode == "") //没有输入
        return;
    QString existBarCode = ui->Goods_BarCode_lineEdit->text();
    if(existBarCode == ""){ //当前还没有输入，则新条码的当第一个条码
        xdebug<< newBarCode;
        ui->Goods_BarCode_lineEdit->setText(newBarCode);
        return;
    }
    existBarCode += ";";
    existBarCode += newBarCode;
    xdebug << existBarCode;
    ui->Goods_BarCode_lineEdit->setText(existBarCode);
}

void PurchaseWidget::addBarCode(bool checked)
{
    int row = ui->tableView->currentIndex().row();
    if( row < 0) {
        myHelper::ShowMessageBoxError("请先选择一行信息！");
        return;
    }
    QStringList  dataList = m_pStandModel->getData(row);
    QString code = myHelper::showInputBox(QString("商品:%1").arg(dataList[0]), "新条码：");
    if(code == "")
        return;
    //xdebug << value;
    QString errorString;
    if(!m_pGoodsSqlhelp->addBarCode(dataList[0], code, errorString)) {
        myHelper::ShowMessageBoxError("错误："+errorString);
    } else {
        myHelper::ShowMessageBoxInfo("添加成功！");
        dataList.removeAt(1);
        m_pStandModel->insertOneRow(dataList, code);
    }
}

bool PurchaseWidget::eventFilter(QObject *watched, QEvent *event)
{
    //回车查询
    if(watched == ui->lineEdit && event->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_Enter) {
            on_Query_pushButton_clicked();
            return true;
        }
        return false;
    }
    //右键菜单栏
    if(watched == ui->tableView && event->type() == QEvent::ContextMenu) {
        QContextMenuEvent* contextMenuEvent = static_cast<QContextMenuEvent *>(event);
        m_popMenu->exec(QCursor::pos());
    }
}


void PurchaseWidget::on_flush_pushButton_clicked()
{
    on_Query_pushButton_clicked();
}

/*
 *关闭进度条动画的实现
*/
void PurchaseWidget::closeProgressBarAnimation()
{
    QPropertyAnimation *animation = new QPropertyAnimation(ui->progressBar, "Opacity");
    animation->setDuration(1000);
    animation->setStartValue(1);
    animation->setEndValue(0);
    animation->start();
    connect(animation, SIGNAL(finished()), ui->progressBar, SLOT(hide()));
}
//导入
void PurchaseWidget::on_exportIn_pushButton_clicked()
{

     Excel excel;
     excel.open();
     int rows = excel.getRowsCount();
     int columns = excel.getColumnsCount();

     ui->progressBar->setMinimum(0);
     ui->progressBar->setMaximum(rows);
     ui->progressBar->setValue(0);
     ui->progressBar->setVisible(true);

     if(rows == 0 || columns <= 3) {
         myHelper::ShowMessageBoxError("错误：数据列太少");
         return;
     }

     for(int i = 2; i <= rows; ++i) {
         QStringList rowData;
         ui->progressBar->setValue(i-1);
         for(int j = 1; j <= columns; ++j) {
             xdebug << excel.getCell(i, j);
             rowData << excel.getCell(i, j).toString();
         }
         QString info;
         QString barCode;
         xdebug<<rowData.at(0);
         if(m_pGoodsSqlhelp->istGoodIdExist(rowData.at(0), info)) {       //编号存在直接下一行
             myHelper::ShowMessageBoxError(rowData.at(0)+"编号已存在");
             continue;
         } else {
             QString unitName = rowData.at(5);
             QString categorieName = rowData.at(6);
             if(!m_pGoodsSqlhelp->isUnitExist(unitName))
                 m_pGoodsSqlhelp->addUnit(unitName);
             if(!m_pGoodsSqlhelp->isCategorieExist(categorieName))
                 m_pGoodsSqlhelp->addCategorie(categorieName);
             int unitNum = m_pGoodsSqlhelp->selectUnitNum(unitName);
             int categorieNum = m_pGoodsSqlhelp->selectCategorieNum(categorieName);
             xdebug<<unitName<<categorieName<<unitNum<<categorieNum;
             rowData[5] = QString::number(unitNum);
             rowData[6] = QString::number(categorieNum);
             barCode = rowData.at(1);
             rowData.removeAt(1);
             if(!m_pGoodsSqlhelp->addGood(rowData, barCode)) {
                 myHelper::ShowMessageBoxError(rowData.at(0)+"插入失败");
                 break;
             }
         }
     }
     ui->progressBar->setValue(rows);
     closeProgressBarAnimation();
     myHelper::ShowMessageBoxInfo("导入完成！");
     //重新绑定种类
     ui->Goods_Categories_comboBox->clear();
     m_pGoodsSqlhelp->BindDataToCombox(g_categorieTableName, g_CategorieColumn[Categorie_Name],
                                       g_CategorieColumn[Categorie_Id], ui->Goods_Categories_comboBox);
     //重新绑定单位
     ui->Goods_Units_comboBox->clear();
     m_pGoodsSqlhelp->BindDataToCombox(g_unitTableName, g_unitColumn[Unit_Name],
                                       g_unitColumn[Unit_Id], ui->Goods_Units_comboBox);
}

//导出
void PurchaseWidget::on_exportOut_pushButton_clicked()
{

    Excel excel;
    excel.addSheet("goods");
    xdebug << "rows:" << m_pStandModel->rowCount() << ", cols:" << m_pStandModel->columnCount();

    QVariantList header;
    for (int i = 0; i < m_pStandModel->columnCount(); ++i) {
        header.append(m_pStandModel->headerData(i, Qt::Horizontal));
    }
    excel.appendRow(header);
    for (int i = 0; i < m_pStandModel->rowCount(); ++i) {
        QVariantList oneRow;
         ui->progressBar->setValue(i);
        for (int j = 0; j < m_pStandModel->columnCount(); ++j) {
            QModelIndex index = m_pStandModel->index(i, j);
            oneRow.append(m_pStandModel->data(index));
        }
        excel.appendRow(oneRow);
    }
    excel.save();
    myHelper::ShowMessageBoxInfo("导出完成！");
}
